#encoding=utf8
import datetime
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.db.models.query_utils import Q
from django.http import *
from django.shortcuts import *

from trp.models import * 
from utils.decorators import *
from utils.utils import date_range_array, date_region_intersect, OrgType
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
import json
from website.settings import LOGGER as logger
from trp.views.costlog import get_cost_by_date,get_cost_by_org
from django.template.defaultfilters import floatformat

@login_required
def main(request):
    end = datetime.date.today()-datetime.timedelta(days=1)
    start =end - datetime.timedelta(days=6)
    print start,end
    org = request.user.account.organization.all()[0]
    result = __index_report(start, end, org,None)
    del result["data"]
    flag = (org.type==OrgType.PLATFORM)
    return render_to_response('trp/index.html', {'user' : request.user, 'page' : 'index',"total":result.get("total_data"),"is_platform":flag})
    
@login_required_ajax
def index_report(request):
    result = None
    try :
#         params = json.loads(request.body)
        params = request.GET
        start_date = params.get("start")
        end_date = params.get("end")
        type=params.get("type")
        if not start_date  or not end_date :
            end = datetime.date.today()-datetime.timedelta(days=1)
            start=end- datetime.timedelta(days=6)
        else :
            start = datetime.datetime.strptime(start_date,"%Y-%m-%d").date()
            end = datetime.datetime.strptime(end_date,"%Y-%m-%d").date()
        if start > end :
            start,end=end,start

        org = request.user.account.organization.all()[0]
        result = __index_report(start,end,org,type)
        del result["total_data"]
        return JsonResponse(result)
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":"bad request"})


def __index_report(start,end,org,type):
    if org.type==OrgType.PLATFORM :
        result =  __platform_report(start, end,type)
    else :
        result = __vendor_report(start, end, org,type)
    return result

def __platform_report(start,end,type):
    base_data_by_date={}
    args = []
    kwargs = {}
    if not type:
        report_data = DailyReport.objects.filter(date__range=(start,end)).\
                                                    values_list("date","pv","uv","click","cost")        
    else:
        type=int(type)
        kwargs['position__media__type']=type
        report_data=DailyMediaTypeReport.objects.filter(type=type,date__range=(start,end)).\
                                                    values_list("date","pv","uv","click","cost")
    for pd in report_data :
            d,pv,uv,click,cost=pd
            base_data_by_date[d]=(pv,uv,click,cost)

    #广告位每日报表数据
    position_data = DailyPositionReport.objects.select_related().\
                                                    filter(date__range=(start,end)).\
                                                    values_list("date","pv","uv","click","cost","position_id")
    position_data_by_day = {}                                                    
    for pd in position_data :
        d,pv,uv,click,cost,position_id=pd
        position_data_by_day[(d,position_id)]=(pv,uv,click,cost)        
   
    args.append(Q(start__range=(start,end)) | Q(end__range=(start,end))|Q(start__lte=start,end__gte=end)|Q(start__gte=start,end__lte=end))
    kwargs['deleted'] = False
    
       
#     resources=Resource.objects.select_related().filter(*args,**kwargs)

    traffics = Traffic.objects.filter(*args,**kwargs)        
    date_arr = date_range_array(start,end)
    resource_cost=dict([(x,0) for x in date_arr])
    for traffic in traffics:        
        bid_type= traffic.bid_type
    #             0-> CPD  1-> CPM
        date_region = date_region_intersect(start,end,traffic.start,traffic.end)
        if date_region :
            bid_date_arr = date_range_array(date_region[0],date_region[1]) 
            for d in bid_date_arr:
                if bid_type==0 :
                    resource_cost[d]+=traffic.bid_price
                elif bid_type==1:
                    resource_cost[d]+=position_data_by_day.get((d,traffic.position.id),(0,0,0,0))[0]*traffic.bid_price*1.0/1000
    
    total_PV = 0
    total_click=0
    total_cost = 0
    total_income = 0
    total_profit=0
    total_sale=0
    data=[]
    result = {}
    pv_days = 0
    click_days=0
    cost_days=0 
    sale_days=0

    for d in date_arr :
        pv,uv,click,income = base_data_by_date.get(d,(0,0,0,0))
        tmp = {}
        tmp["date"]=d.strftime("%Y-%m-%d")
        tmp["pv"]=pv
        if pv !=0 :
            pv_days+=1
        tmp["uv"]=uv
        tmp["click"]=click
        if click !=0 :
            click_days+=1
        tmp["ctr"]= 0
        if pv != 0 :
            tmp["ctr"] = floatformat(click*1.0/pv,arg=-2)
        tmp["cost"]=floatformat(resource_cost.get(d,0.0),arg=-2)
        if tmp["cost"] !=0.0 :
            cost_days+=1
        tmp["bid"]=floatformat(income,arg=-2)
        tmp["sale_income"]=floatformat(get_cost_by_date(d,type),arg=-2)
        if tmp["sale_income"]!=0.0:
            sale_days+=1
        tmp["profit"]=floatformat(float(tmp["bid"])+float(tmp["sale_income"])-float(tmp["cost"]),arg=-2)
        data.append(tmp)
        
        total_PV+=pv
        total_click +=click
        total_income +=income
        total_sale+=float(tmp["sale_income"])
        total_cost +=float(tmp["cost"])
        total_profit=total_income-total_cost
    total={
           "pv":total_PV,
           "click":total_click,
           "cost":floatformat(total_income,arg=-2),
           "profit":floatformat(total_profit,arg=-2),
           "sale":floatformat(total_sale,arg=-2),
           }
    if pv_days==0 :
        total["pv_per_day"]=0
    else :
        total["pv_per_day"]=total_PV/pv_days
    if click_days ==0 :
        total["click_per_day"]=0
    else :
        total["click_per_day"]=total_click/click_days
    if cost_days==0 :
        total["cost_per_day"]=0
    else :
        total["cost_per_day"]=floatformat(float(total["cost"])*1.0/cost_days,arg=-2)
    if sale_days==0:
        total["sale_per_day"]=0
    else:
        total["sale_per_day"]=floatformat(float(total["sale"])*1.0/sale_days,arg=-2)
    result["data"]=data
    result["total_data"]=total
    return result 

def __vendor_report(start,end ,org,type):
    if not type:
        report_data = DailyOrganizationReport.objects.filter(date__range=(start,end),organization = org).\
                                                values_list("date","pv","uv","click","cost")
    else:
        type=int(type)
        report_data = DailyOrganizationMediaTypeReport.objects.filter(date__range=(start,end),organization = org,type=type).\
                                                values_list("date","pv","uv","click","cost")
    base_data_by_date={}
    for pd in report_data :
        d,pv,uv,click,cost=pd
        base_data_by_date[d]=(pv,uv,click,cost)

    date_arr = date_range_array(start,end)
    total_PV = 0
    total_click=0
    total_cost = 0
    total_sale=0
    data=[]
    result={}
    pv_days = 0
    click_days=0
    cost_days=0 
    sale_days=0
    for d in date_arr :
        pv,uv,click,cost = base_data_by_date.get(d,(0,0,0,0))
        tmp = {}
        tmp["date"]=d.strftime("%Y-%m-%d")
        tmp["pv"]=pv

        total_PV +=pv
        if pv !=0 :
            pv_days+=1
        tmp["uv"]=uv
        tmp["click"]=click
        total_click +=click
        if click !=0 :
            click_days+=1
        tmp["ctr"]= 0
        if pv != 0 :
            print "pv",pv,d
            tmp["ctr"] = floatformat(click*1.0/pv,arg=-5)
        tmp["cost"]=cost
        total_cost +=tmp["cost"]
        if tmp["cost"] !=0.0 :
            cost_days+=1
        tmp["sale_income"]=floatformat(get_cost_by_org(d,org.id,type),arg=-2)
        if tmp["sale_income"]!=0.0:
            sale_days+=1
        total_sale+=float(tmp["sale_income"])
        data.append(tmp)
    total={"pv":total_PV,"click":total_click,"cost":total_cost,"sale":total_sale}
    print total
    if pv_days==0 :
        total["pv_per_day"]=0
    else :
        total["pv_per_day"]=total["pv"]/pv_days
    if click_days ==0 :
        total["click_per_day"]=0
    else :
        total["click_per_day"]=total["click"]/click_days
    if cost_days==0 :
        total["cost_per_day"]=0
    else :
        total["cost_per_day"]=floatformat(total["cost"]*1.0/cost_days,arg=-2)
    if sale_days==0:
        total["sale_per_day"]=0
    else:
        total["sale_per_day"]=floatformat(total["sale"]*1.0/sale_days,arg=-2)
    result["data"]=data
    result["start"]=start.strftime("%Y-%m-%d")
    result["end"]=end.strftime("%Y-%m-%d")
    result["total_data"]=total
    return result 
